package com.gvfish.backingbean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import com.gvfish.core.Action;
import com.gvfish.entity.Link;
import com.gvfish.service.LinkManager;


@ManagedBean
public class LinkBean {

	ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
	LinkManager linkManager = (LinkManager) ctx.getBean("linkManager");
	private List<Link> links;
	private Link link=new Link();
	private boolean editModel;

	private DataModel<Link> linkModel = new ListDataModel<Link>();
	{
		linkModel.setWrappedData(linkManager.findAll());
	}
	
	public DataModel<Link> getAllLinks(){
		return linkModel;
	}

	public LinkBean() {
		links = linkManager.findAll();
	}

	/**
	 * 跳转到添加链接页面
	 * @return
	 */
	public String add() {
		this.link=new Link();
		return "success";
	}

	/**
	 * 进入修改页面
	 * @return
	 */
	public String edit() {
		this.link = (Link) linkModel.getRowData();
		System.out.println(link);
		this.link = linkManager.find(link.getId());
		setEditModel(true);
		return "success";
	}

	/**
	 * 删除链接
	 * @param event
	 */
	public void del(ActionEvent event) {
		this.link = (Link) linkModel.getRowData();
		linkManager.del(link.getId());
		links = linkManager.findAll();
		linkModel.setWrappedData(links);
	}
	/**
	 * 保存链接
	 * @return
	 */
	public String save() {
		linkManager.save(link);
		this.links = linkManager.findAll();
		linkModel.setWrappedData(links);
		this.link = new Link();
		return "success";
	}
	public String update(){
		System.out.println("in link update");
		linkManager.update(this.link);
		this.editModel=false;
		link = new Link();
		linkModel.setWrappedData(linkManager.findAll());
		return Action.SUCCESS;
	}


	public void setLink(Link link) {
		System.out.println("in set link");
		this.link = link;
	}

	public Link getLink() {
		return link;
	}

	public void setEditModel(boolean editModel) {
		this.editModel = editModel;
	}

	public boolean isEditModel() {
		return editModel;
	}

	public void setLinks(List<Link> links) {
		this.links = links;
	}

	public List<Link> getLinks() {
		return links;
	}

}
